package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 去交易
     *
     * @return TradeVo
     */
    @Override
    public TradeVo orderTradeData() {
        //1.获取userId
        Long userId = SecurityContextHolder.getUserId();
        //2.调用远程，获取当前用户购物车中打钩的商品集合 List<CartInfo>
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL == cartCheckedListResult.getCode()) {
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        List<CartInfo> checkedCartInfoList = cartCheckedListResult.getData();
        if (CollectionUtils.isEmpty(checkedCartInfoList)) {
            throw new ServiceException("数据为空");
        }
        //3.转换数据类型 List<OrderItem>
        List<OrderItem> orderItemList = checkedCartInfoList.stream().map((cartInfo) -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            //orderItem.setSkuPrice(cartInfo.getSkuPrice());
            return orderItem;
        }).toList();


        //4.计算总价格
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
//            orderItem.getSkuPrice().divide()
//            orderItem.getSkuPrice().add()
//            orderItem.getSkuPrice().subtract()
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        //5.封装TradeVo
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        String tradeNo = generateTradeNo(userId);
        tradeVo.setTradeNo(tradeNo);

        //6.返回TradeVo
        return tradeVo;
    }


    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 下订单业务逻辑：
     * 1.验证用户重复提交表单
     * 2.验证表单参数是否空
     * 3.校验价格变化
     * 4.校验库存锁定库存
     * 5.保存订单（订单表、订单项表、订单日志表）
     * 6.删除购物车选中商品
     * 7.发送延迟消息，(未支付)关闭订单
     *
     * @param orderForm 提交订单数据
     * @return 订单id
     */
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //1.验证用户重复提交表单
        /* 获取缓存数据和删除缓存数据不是原子性的，可能出现并发问题。需要通过Lua脚本来保证原子性。
        String tradeNo = orderForm.getTradeNo(); //交易页面提交的交易流水号，5分钟有效。
        //从缓存获取交易流水号，进行判断
        Long userId = SecurityContextHolder.getUserId();
        String tradeNoKey = "user:tradeNo:"+userId;
        String redisTradeNo = (String)redisTemplate.opsForValue().get(tradeNoKey); //可能过期失效或验证重复后删除。
        if(tradeNo!=null && !tradeNo.equals(redisTradeNo)){
            throw new ServiceException("重复提交");
        }
        redisTemplate.delete(tradeNoKey);*/

        //获取表单提交的订单流水号
        String tradeNo = orderForm.getTradeNo();

        Long userId = SecurityContextHolder.getUserId();
        //交易流水号缓存的key
        String tradeNoKey = "user:tradeNo:" + userId;
        //获取缓存交易流水号
        String redisTradeNo = (String) redisTemplate.opsForValue().get(tradeNoKey);

        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        Long result = (Long) redisTemplate.execute(new DefaultRedisScript(scriptText, Long.class), Arrays.asList(tradeNoKey), tradeNo);
        if (result == 0) { //可能过期失效或验证重复后删除过。
            throw new ServiceException("重复提交");
        }

        //2.验证表单参数是否空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("数据不能为空");
        }

        //3.校验价格变化
        //获取数据库最新价格，进行判断
        List<Long> skuIdList = orderItemList.stream().map((orderItem) -> orderItem.getSkuId()).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData(); //最新价格
        Map<Long, BigDecimal> skuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        //价格有不一致的，需要更新购物车，抛异常，
        StringBuilder priceChangeStr = new StringBuilder("");
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuIdToSalePriceMap.get(orderItem.getSkuId())) != 0) {
                //priceChangeStr += "商品【"+orderItem.getSkuName()+"】价格改变了;";
                priceChangeStr = priceChangeStr.append("商品【" + orderItem.getSkuName() + "】价格改变了;");
            }
        }
        if (StringUtils.hasText(priceChangeStr.toString())) { //不能空说明有价格不一致情况，抛异常不下单了。还需要更新购物车价格
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            throw new ServiceException(priceChangeStr.toString());
        }

        //4.校验库存锁定库存
        List<SkuLockVo> skuLockVoList = orderForm.getOrderItemList().stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            //skuLockVo.setIsHaveStock(false); //默认 false
            return skuLockVo;
        }).toList();
        R<String> stringResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == stringResult.getCode()) {
            throw new ServiceException(stringResult.getMsg());
        }
        if (StringUtils.hasText(stringResult.getData())) {
            throw new ServiceException(stringResult.getData());
        }

        //5.保存订单（订单表、订单项表、订单日志表）
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            //....解锁库存  (发送消息异步解锁库存)
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }

        //6.删除购物车选中商品
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);

        //7.发送延迟消息，(未支付)关闭订单
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId),
                MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    /**
     * 保存订单：
     * 1.保存订单数据
     * 2.保存多个订单项数据
     * 3.保存订单日志
     *
     * @param orderForm 提交订单数据
     * @return 订单id
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Long saveOrder(OrderForm orderForm) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        //1.保存订单数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); //实付总价格(含优惠价格和运费)
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount); //商品总价格(不含优惠价格和运费)
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderInfoMapper.insert(orderInfo); //主键回填

        //2.保存多个订单项数据
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem); //   循环调用mapper操作数据库效率比较低，将来去进行优化。TODO
        }

        //3.保存订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setOperateUser("用户"); //操作人：用户；系统；后台管理员
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }


    @Override
    public TradeVo buy(Long skuId) {
        //1.获取userId
        Long userId = SecurityContextHolder.getUserId();

        //2.根据skuId获取ProductSku
        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()) {
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSku productSku = productSkuResult.getData();

        //3.转换数据类型 List<OrderItem>
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(productSku.getId());
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);

        //4.计算总价格
        BigDecimal totalAmount = orderItem.getSkuPrice();


        //5.封装TradeVo
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        String tradeNo = generateTradeNo(userId);
        tradeVo.setTradeNo(tradeNo);

        //6.返回TradeVo
        return tradeVo;
    }


    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityContextHolder.getUserId();
        //获取订单列表
        List<OrderInfo> orderInfoList = orderInfoMapper.selectUserOrderInfoList(userId, orderStatus);

        //获取每一个订单的订单项集合，封装在订单对象中。一起返回
        if (!CollectionUtils.isEmpty(orderInfoList)) {

            List<Long> orderInfoIdList = orderInfoList.stream().map((orderInfo -> orderInfo.getId())).toList();

            List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderInfoIdList));
            Map<Long, List<OrderItem>> orderIdToOrderItemListMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));

            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(orderIdToOrderItemListMap.get(orderInfo.getId()));
            }

            return orderInfoList;
        }

        return new ArrayList<OrderInfo>();
    }

    @Transactional
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户手动取消订单");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户手动取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }


    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Transactional
    @Override
    public void processPaySucess(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper
                .selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo)
                        .select(OrderInfo::getId, OrderInfo::getOrderStatus, OrderInfo::getPaymentTime));
        if (orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}